<!DOCTYPE html>

<html>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<script type="text/javascript" src="paho-mqtt-1.0.1.js" charset="UTF-8"></script>

	<script type="text/javascript">
		// MQTT 客户端连接
		var mqttClient;
	
		// 打开窗口时连接mqtt服务器
		window.onload = function() {
			// 连接mqtt服务器
			connect(wsurl.value, "ZyWebClient1");
		}

		// 监听窗口关闭事件，当窗口关闭时，主动去关闭连接，
		// 防止连接还没断开就关闭窗口，server端会抛异常。
		window.onbeforeunload = function() {
			disconnect();
		}
		
		function connect(url, clientId) {
			print("连接到 MQTT 服务器 " + url + " ...");
			var client = new Paho.MQTT.Client(url, clientId);

			// called when the client loses its connection
			client.onConnectionLost = function (responseObject) {
				if (responseObject.errorCode !== 0) {
					print("onConnectionLost:" + responseObject.errorMessage);
				}
			}

			// called when a message arrives
			client.onMessageArrived = function (message) {
				print(message.payloadString);
			}
			
			// connect the client
			client.connect({
				onSuccess: function (invocationContext) {
					print("连接到 MQTT 服务器成功！");
					mqttClient = client;
					client.subscribe('test');
					publish('test', 'hello from web page');
				},
				onFailure: function (invocationContext, errorCode, errorMessage) {
					print("连接到 MQTT 服务器失败！" + errorMessage);
				},
			});
		}
		
		function disconnect() {
			if(typeof mqttClient !== "object") { return; }
			mqttClient.disconnect();
		}

		// 发布消息
		function publish(topic, message) {
			if(typeof mqttClient !== "object") { return; }
			message = new Paho.MQTT.Message(message);
			message.destinationName = topic;
			mqttClient.send(message);
		}

		// 将消息显示在网页上
		function print(message) {
			log.value += message + '\r\n';
		}
	</script>

	<style>
		* {
			font-family: Consolas;
			font-size: 26px;
		}
		
		#wsurl {
			width: 920px;
		}
	</style>

	<head>
		<title>Paho-MQTT-WebSocket测试</title>
	</head>

	<body>
		<input type="text" id="wsurl" cols="64" spellcheck="false" value="wss://ehome.szwistar.com/mqtt/"/>
		<br>
		<br>
		<textarea id="text" rows="4" cols="64" spellcheck="false">在此输入要发送的数据</textarea>
		<br>
		<button onclick="connect(wsurl.value, 'ZyWebClient1')">建立连接</button>
		<button onclick="publish('test', text.value)">发送消息</button>
		<button onclick="log.value = ''">消除日志</button>
		<button onclick="disconnect()">关闭连接</button>
		<br>
		<textarea id="log" rows="60" cols="64" readonly="readonly"></textarea>
	</body>

</html>